#!/bin/bash

# Git环境Docker环境清理脚本

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 配置变量
IMAGE_NAME="git-env"
TAG="latest"
FULL_IMAGE_NAME="${IMAGE_NAME}:${TAG}"
CONTAINER_NAME="git-env-dev"

echo -e "${BLUE}清理Git环境Docker环境${NC}"

# 检查Docker是否运行
if ! docker info &> /dev/null; then
    echo -e "${RED}错误: Docker服务未运行${NC}"
    exit 1
fi

# 停止并删除容器
echo -e "${BLUE}停止并删除容器...${NC}"
if docker ps -a --format "{{.Names}}" | grep -q "^${CONTAINER_NAME}$"; then
    echo -e "${YELLOW}停止容器 ${CONTAINER_NAME}${NC}"
    docker stop "${CONTAINER_NAME}" || true
    echo -e "${YELLOW}删除容器 ${CONTAINER_NAME}${NC}"
    docker rm "${CONTAINER_NAME}" || true
else
    echo -e "${YELLOW}容器 ${CONTAINER_NAME} 不存在${NC}"
fi

# 删除镜像
echo -e "${BLUE}删除Docker镜像...${NC}"
if docker images --format "{{.Repository}}:{{.Tag}}" | grep -q "^${FULL_IMAGE_NAME}$"; then
    echo -e "${YELLOW}删除镜像 ${FULL_IMAGE_NAME}${NC}"
    docker rmi "${FULL_IMAGE_NAME}" || true
else
    echo -e "${YELLOW}镜像 ${FULL_IMAGE_NAME} 不存在${NC}"
fi

# 停止docker-compose服务
if [ -f "docker-compose.dev.yml" ]; then
    echo -e "${BLUE}停止docker-compose服务...${NC}"
    docker-compose -f docker-compose.yml -f docker-compose.dev.yml down -v --remove-orphans || true
fi

# 清理相关数据卷
echo -e "${BLUE}清理相关数据卷...${NC}"
docker volume ls --format "{{.Name}}" | grep -E "(postgres|redis|git)" | while read volume; do
    echo -e "${YELLOW}删除数据卷 ${volume}${NC}"
    docker volume rm "${volume}" || true
done

# 清理网络
echo -e "${BLUE}清理Docker网络...${NC}"
docker network ls --format "{{.Name}}" | grep -E "(git|git-env)" | while read network; do
    echo -e "${YELLOW}删除网络 ${network}${NC}"
    docker network rm "${network}" || true
done

# 清理日志文件
echo -e "${BLUE}清理日志文件...${NC}"
if [ -d "logs" ]; then
    find logs -type f -name "*.log" -exec rm -f {} \;
    find logs -type f -name "*.pid" -exec rm -f {} \;
    echo -e "${GREEN}日志文件已清理${NC}"
fi

# 清理临时文件
echo -e "${BLUE}清理临时文件...${NC}"
find . -type f -name "*.tmp" -exec rm -f {} \;
find . -type f -name ".DS_Store" -exec rm -f {} \;

# Docker系统清理
echo -e "${BLUE}执行Docker系统清理...${NC}"
docker system prune -f

echo -e "${GREEN}Git环境清理完成!${NC}"

# 显示重建信息
echo -e "${BLUE}=== 重建环境 ===${NC}"
echo -e "${YELLOW}重新构建镜像: ./build.sh${NC}"
echo -e "${YELLOW}重新启动环境: ./run.sh${NC}"